/**
 * config start
 */
const path = require('path');
const chalk = require('chalk');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

const config = require('./config');

const { __DEV__, __PROD__ } = config.globals;
const APP_ENTRY = path.resolve(__dirname, './client/views/index.jsx');


let cssLoader = ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [{
        loader: 'css-loader',
        options: {
            modules: true,
            importLoaders: 2,
            localIdentName: '[name]__[local]___[hash:base64:5]'
        },
    }, {
        loader: 'postcss-loader',
    }]
});

let cssLoaderWithoutModules = ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [{
        loader: 'css-loader',
    }, {
        loader: 'postcss-loader',
    }]
});

let lessLoader = ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [{
        loader: 'css-loader',
        options: {
            modules: true,
            localIdentName: '[name]__[local]___[hash:base64:5]'
        },
    }, {
        loader: 'postcss-loader',
    }, {
        loader: 'less-loader',
    }],
});

let lessLoaderWithoutModules = ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [{
        loader: 'css-loader',
    }, {
        loader: 'postcss-loader',
    }, {
        loader: 'less-loader',
    }],
});

const getConfig = function (webpackConfig) {
    webpackConfig.entry = ['babel-polyfill', APP_ENTRY];

    webpackConfig.module.rules.push(
        {
            test: /\.jsx?$/,
            use: [
                'babel-loader'
            ],
        },
        {
            test: /\.less$/,
            use: lessLoader,
            exclude: [/node_modules/, /ec_modules/],
        },
        {
            test: /\.css$/,
            use: cssLoader,
            exclude: [/node_modules/, /ec_modules/],
        },
        {
            test: /\.less$/,
            use: lessLoaderWithoutModules,
            include: [/node_modules/, /ec_modules/],
        },
        {
            test: /\.css$/,
            use: cssLoaderWithoutModules,
            include: [/node_modules/, /ec_modules/],
        }
    );


    webpackConfig.output = {
        filename: 'js/[name]-[chunkhash].js',
        chunkFilename: 'js/[name]-[chunkhash].js',
        path: path.resolve(__dirname, '../dist/'),
        publicPath: './',
    };

    webpackConfig.devtool = "#source-map";
    webpackConfig.plugins.push(
        new ExtractTextPlugin('css/[name].[contenthash].css', {
            allChunks: true,
        }),
        new webpack.HashedModuleIdsPlugin(),
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, './client', 'index.html'),
            hash: false,
            filename: 'index.html',
            inject: 'body',
        }),
        new BundleAnalyzerPlugin({
            // Can be `server`, `static` or `disabled`.
            // In `server` mode analyzer will start HTTP server to show bundle report.
            // In `static` mode single HTML file with bundle report will be generated.
            // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
            analyzerMode: 'static',
            // Host that will be used in `server` mode to start HTTP server.
            analyzerHost: '127.0.0.1',
            // Port that will be used in `server` mode to start HTTP server.
            analyzerPort: 8888,
            // Path to bundle report file that will be generated in `static` mode.
            // Relative to bundles output directory.
            reportFilename: path.resolve(__dirname, '../dist/webpackAnalyzer/report.html'),
            // Module sizes to show in report by default.
            // Should be one of `stat`, `parsed` or `gzip`.
            // See "Definitions" section for more information.
            defaultSizes: 'parsed',
            // Automatically open report in default browser
            openAnalyzer: true,
            // If `true`, Webpack Stats JSON file will be generated in bundles output directory
            generateStatsFile: true,
            // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
            // Relative to bundles output directory.
            statsFilename: path.resolve(__dirname, '../dist/webpackAnalyzer/stats.json'),
            // Options for `stats.toJson()` method.
            // For example you can exclude sources of your modules from stats file with `source: false` option.
            // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
            statsOptions: null,
            // Log level. Can be 'info', 'warn', 'error' or 'silent'.
            logLevel: 'info'
        }),


        new webpack.DllReferencePlugin({
            context: path.join(__dirname, `../../dll`),
            manifest: path.resolve(__dirname, `../../dll/dist/manifest-react.json`),
        }),
        new webpack.DllReferencePlugin({
            context: path.join(__dirname, `../../dll`),
            manifest: path.resolve(__dirname, `../../dll/dist/manifest-mobx.json`),
        }),
        new webpack.DllReferencePlugin({
            context: path.join(__dirname, `../../dll`),
            manifest: path.resolve(__dirname, `../../dll/dist/manifest-babel.json`),
        }),


        new AddAssetHtmlPlugin({
            filepath: path.resolve(__dirname, `../../dll/dist/dll.mobx.js`),//这里要写dll的输出目录，手动copy到别的目录不管用
            outputPath: '../dist/js/',// dll文件会被复制到这个目录下
            publicPath: './js/',//html中对js的引用
            includeSourcemap: false,
            hash: true,
        }),
        new AddAssetHtmlPlugin({
            filepath: path.resolve(__dirname, `../../dll/dist/dll.react.js`),//这里要写dll的输出目录，手动copy到别的目录不管用
            outputPath: '../dist/js/',// dll文件会被复制到这个目录下
            publicPath: './js/',//html中对js的引用
            includeSourcemap: false,
            hash: true,
        }),
        new AddAssetHtmlPlugin({
            filepath: path.resolve(__dirname, `../../dll/dist/dll.babel.js`),//这里要写dll的输出目录，手动copy到别的目录不管用
            outputPath: '../dist/js/',// dll文件会被复制到这个目录下
            publicPath: './js/',//html中对js的引用
            includeSourcemap: false,
            hash: true,
        }),

        new UglifyJSPlugin({//https://doc.webpack-china.org/plugins/uglifyjs-webpack-plugin/
            sourceMap: true,//只有设置了devtool才会生效
            beautify: true,//2.x要放在这里
            mangle:false,
            uglifyOptions: {
                sourceMap: true,
                ie8: false,
                ecma: 8,
                parse: {},
                mangle: false,//不混淆名字
                output: {
                    comments: false,
                    beautify: true,//3.x要放这里
                    keep_quoted_props: true,
                },
                warnings: false,
                compress: {
                    keep_fnames: true,
                }
            }

        }),
    );

    return webpackConfig;
}

module.exports = {
    getConfig
};
